package org.groupg.practice;

import org.jgrapht.*;
import org.jgrapht.graph.*;
import org.jgrapht.traverse.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;

public class ConcurrentDAGTraversal {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个有向图
        DefaultDirectedGraph<String, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);

        // 添加节点和边
        graph.addVertex("A");
        graph.addVertex("B");
        graph.addVertex("C");
        graph.addVertex("D");
        graph.addVertex("E");
        graph.addVertex("F");
        graph.addVertex("G");

        graph.addEdge("A", "B");
        graph.addEdge("F", "B");
        graph.addEdge("B", "C");
        graph.addEdge("G", "D");
        graph.addEdge("C", "D");
        graph.addEdge("D", "E");

        // 计算拓扑排序
        List<String> topologicalOrder = new ArrayList<>();
        TopologicalOrderIterator<String, DefaultEdge> toi = new TopologicalOrderIterator<>(graph);
        toi.forEachRemaining(topologicalOrder::add);

        // 创建一个线程池
        ExecutorService executor = Executors.newFixedThreadPool(4);

        // 并发处理有度节点
        for (String vertex : topologicalOrder) {
            if (graph.inDegreeOf(vertex) > 0 || graph.outDegreeOf(vertex) > 0) {
                executor.submit(() -> {

                    // 模拟一些处理时间
                    try {
                        Thread.sleep(100);
                         // 处理节点逻辑
                    System.out.println("Thread : [" + Thread.currentThread().getName() + "] time :["+ LocalDateTime.now() +"] Processing node: [" + vertex);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            }
        }

        // 关闭线程池并等待所有任务完成
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.MINUTES);
    }
}